import {Injectable, UnauthorizedException} from '@nestjs/common';
import {PassportStrategy} from '@nestjs/passport';
import { Strategy } from 'passport-http-bearer';
import {AuthService} from './auth.service';

@Injectable()
export class HttpStrategy extends PassportStrategy(Strategy) {

    constructor(private readonly authService: AuthService) {
        super();
    }

    async validate(token: any, done: Function) {
        let authObject: {username: string, password: string} = null;
        console.log(token);
        authObject = {username: 'root', password: '123456'};
        // const decoded = Buffer.from(token, 'base64').toString();
        // console.log(decoded);
        try {
            // authObject = JSON.parse(decoded);
            // console.log(authObject);
            const user = await this.authService.validateUser(authObject);
            if (!user) {
                return done(new UnauthorizedException(), false);
            }
            done(null, user);
        } catch (e) {
            console.log(e)
            return done(new UnauthorizedException(), false);
        }
    }
}
